package org.pmt.first.kms.screen

import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.ExperimentalSharedTransitionApi
import androidx.compose.animation.SharedTransitionLayout
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.PermanentDrawerSheet
import androidx.compose.material3.ScaffoldDefaults.contentWindowInsets
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.adaptive.ExperimentalMaterial3AdaptiveApi
import androidx.compose.material3.adaptive.layout.ListDetailPaneScaffoldRole
import androidx.compose.material3.adaptive.layout.ThreePaneScaffoldDestinationItem
import androidx.compose.material3.adaptive.navigation.BackNavigationBehavior
import androidx.compose.material3.adaptive.navigation.ThreePaneScaffoldNavigator
import androidx.compose.material3.adaptive.navigation.rememberListDetailPaneScaffoldNavigator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.dream.common.hasScrollingBug
import com.dream.ui.foundation.AniListDetailPaneScaffold
import com.dream.ui.foundation.ListDetailLayoutParameters
import com.dream.ui.foundation.LocalPlatform
import com.dream.ui.foundation.PaneScope
import com.dream.ui.foundation.animation.LocalAniMotionScheme
import com.dream.ui.foundation.layout.AniWindowInsets
import com.dream.ui.foundation.layout.currentWindowAdaptiveInfo1
import com.dream.ui.foundation.layout.paneVerticalPadding
import com.dream.ui.foundation.theme.AniThemeDefaults
import com.dream.ui.foundation.widgets.BackNavigationIconButton
import com.dream.ui.foundation.widgets.KmsWindowInsets
import com.dream.ui.foundation.widgets.TextDefault.Title
import com.dream.ui.foundation.widgets.ifThen
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.launch
import org.jetbrains.compose.ui.tooling.preview.Preview
import org.pmt.first.kms.resource.KmsTheme
import org.pmt.first.kms.resource.StringRes.getName
import org.pmt.first.kms.screen.theme.transparentAppBarColors
import org.pmt.first.resource.IconRes.getIcon
import org.pmt.first.resource.SettingsTab
import org.pmt.first.resource.orDefault

/**
 * Author: pengmutian
 * Date: 2025/3/17 12:26
 * Description: SettingScreen
 */
@OptIn(
    ExperimentalSharedTransitionApi::class, ExperimentalMaterial3Api::class,
    ExperimentalMaterial3AdaptiveApi::class
)
@Composable
fun SettingScreen(
    navController: NavHostController,
    vm: SettingsViewModel? = null,
    modifier: Modifier = Modifier,
    initialTab: SettingsTab? = null,
    // 应用窗口内容的边衬区域（Insets，即内边距）
    windowInsets: WindowInsets = KmsWindowInsets.safeDrawing,
    navigationIcon: @Composable () -> Unit = {},
) = Surface(color = MaterialTheme.colorScheme.surfaceContainerLowest) {
    val paneContentWindowInsets: WindowInsets = KmsWindowInsets.safeDrawing
    SharedTransitionLayout {
        val listPaneScrollState = rememberScrollState()
        Column {
            TopAppBar(
                title = { Title("设置") },
                navigationIcon = {
                    BackNavigationIconButton(
                        onNavigateBack = {
                            navController.popBackStack()
                        },
                    )
                },
                colors = transparentAppBarColors(),
                scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior(),
                windowInsets = paneContentWindowInsets.only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal)
            )

            Box(
                Modifier
                    .fillMaxHeight()
                    .consumeWindowInsets(paneContentWindowInsets.only(WindowInsetsSides.Top)),
            ) {
                Column(
                    Modifier.consumeWindowInsets(
                        contentWindowInsets.only(WindowInsetsSides.Top),
                    ).padding(16.dp).fillMaxSize().verticalScroll(listPaneScrollState),
                ) {
                    // 应用与界面
                    Text(
                        text = "应用与界面",
                        style = MaterialTheme.typography.titleMedium,
                        color = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    SettingItem(Icons.Filled.Settings, "界面")
                    SettingItem(Icons.Filled.Settings, "主题与色彩")
                    SettingItem(Icons.Filled.Settings, "软件更新")

                    Spacer(modifier = Modifier.height(16.dp))

                    // 数据源与播放
                    Text(
                        text = "数据源与播放",
                        style = MaterialTheme.typography.titleMedium,
                        color = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    SettingItem(Icons.Filled.Settings, "播放器和弹幕过滤")
                    SettingItem(Icons.Filled.Settings, "数据源管理")
                    SettingItem(Icons.Filled.Email, "观看偏好")
                    SettingItem(Icons.Filled.Settings, "弹幕源")
                    Spacer(modifier = Modifier.height(16.dp))

                    // 网络与存储
                    Text(
                        text = "网络与存储",
                        style = MaterialTheme.typography.titleMedium,
                        color = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    SettingItem(Icons.Filled.Settings, "代理")
                    SettingItem(Icons.Filled.Settings, "VPN")

                    // 数据源与播放
                    Text(
                        text = "反馈",
                        style = MaterialTheme.typography.titleMedium,
                        color = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    SettingItem(Icons.Filled.Settings, "播放器和弹幕过滤")
                    SettingItem(Icons.Filled.Settings, "数据源管理")
                    SettingItem(Icons.Filled.Email, "观看偏好")
                    SettingItem(Icons.Filled.Settings, "弹幕源")
                    Spacer(modifier = Modifier.height(16.dp))
                }
            }
        }

    }
}

@OptIn(ExperimentalMaterial3AdaptiveApi::class)
@Composable
@Preview
fun SettingsScreen(
    vm: SettingsViewModel? = null,
    modifier: Modifier = Modifier,
    initialTab: SettingsTab? = null,
    windowInsets: WindowInsets = AniWindowInsets.forPageContent(),
    navigationIcon: @Composable () -> Unit = {},
) {
    var lastSelectedTab by rememberSaveable {
        mutableStateOf(initialTab)
    }
    val navigator: ThreePaneScaffoldNavigator<Nothing?> = rememberListDetailPaneScaffoldNavigator(
        initialDestinationHistory = buildList {
            add(ThreePaneScaffoldDestinationItem(ListDetailPaneScaffoldRole.List))
            if (initialTab != null) {
                add(ThreePaneScaffoldDestinationItem(ListDetailPaneScaffoldRole.Detail))
            }
        },
    )
    val layoutParameters = ListDetailLayoutParameters.calculate(navigator.scaffoldDirective)
    val coroutineScope = rememberCoroutineScope()

    SettingsPageLayout(
        navigator,
        // TODO: 2025/2/14 We should have a SettingsNavController or so to control the tab state
        { lastSelectedTab },
        onSelectedTab = { tab ->
            coroutineScope.launch(start = CoroutineStart.UNDISPATCHED) {
                navigator.navigateTo(ListDetailPaneScaffoldRole.Detail)
                lastSelectedTab = tab
            }
        },
        onClickBackOnListPage = {
            coroutineScope.launch(start = CoroutineStart.UNDISPATCHED) {
                navigator.navigateBack()
            }
        },
        onClickBackOnDetailPage = {
            coroutineScope.launch(start = CoroutineStart.UNDISPATCHED) {
                navigator.navigateBack(BackNavigationBehavior.PopUntilScaffoldValueChange)
            }
        },
        navItems = {
            Title("应用与界面", paddingTop = 0.dp)
            Item(SettingsTab.APPEARANCE)
            Item(SettingsTab.THEME)
            Item(SettingsTab.UPDATE)

            Title("数据源与播放")
            Item(SettingsTab.PLAYER)
            Item(SettingsTab.MEDIA_SOURCE)
            Item(SettingsTab.MEDIA_SELECTOR)
            Item(SettingsTab.DANMAKU)

            Title("网络与存储")
            Item(SettingsTab.PROXY)
            Item(SettingsTab.BT)
            Item(SettingsTab.CACHE)
            Item(SettingsTab.STORAGE)

            Title("其他")
            Item(SettingsTab.ABOUT)
//            if (vm.isInDebugMode) {
            Item(SettingsTab.DEBUG)
//            }
        },
        tabContent = { currentTab ->
            val tabModifier = Modifier
            Column(
                Modifier
                    .verticalScroll(rememberScrollState())
                    .padding(horizontal = SettingsScope.itemExtraHorizontalPadding),
            )
            {
//                when (currentTab) {
//                    SettingsTab.ABOUT -> AboutTab({ vm.debugTriggerState.triggerDebugMode() }, tabModifier)
//                    SettingsTab.DEBUG -> DebugTab(
//                        vm.debugSettingsState,
//                        vm.uiSettings,
//                        tabModifier,
//                    )

//                    else -> SettingsTab(
//                        tabModifier,
//                    ) {
//                        when (currentTab) {
//                            SettingsTab.APPEARANCE -> AppearanceGroup(vm.uiSettings)
//                            SettingsTab.THEME -> ThemeGroup(vm.themeSettings)
//                            SettingsTab.UPDATE -> SoftwareUpdateGroup(vm.softwareUpdateGroupState)
//                            SettingsTab.PLAYER -> PlayerGroup(
//                                vm.videoScaffoldConfig,
//                                vm.danmakuFilterConfigState,
//                                vm.danmakuRegexFilterState,
//                                vm.isInDebugMode,
//                            )
//
//                            SettingsTab.MEDIA_SOURCE -> {
//                                MediaSourceSubscriptionGroup(
//                                    vm.mediaSourceSubscriptionGroupState,
//                                )
//                                MediaSourceGroup(
//                                    vm.mediaSourceGroupState,
//                                    vm.editMediaSourceState,
//                                )
//                            }
//
//                            SettingsTab.MEDIA_SELECTOR -> MediaSelectionGroup(vm.mediaSelectionGroupState)
//                            SettingsTab.DANMAKU -> DanmakuGroup(vm.danmakuSettingsState, vm.danmakuServerTesters)
//                            SettingsTab.PROXY -> GlobalProxyGroup(vm.proxySettingsState, vm.detectedProxy)
//                            SettingsTab.BT -> TorrentEngineGroup(vm.torrentSettingsState)
//                            SettingsTab.CACHE -> AutoCacheGroup(vm.mediaCacheSettingsState)
//                            SettingsTab.STORAGE -> CacheDirectoryGroup(vm.cacheDirectoryGroupState)
//                            SettingsTab.ABOUT -> {} // see above
//                            SettingsTab.DEBUG -> {}
//                            null -> {}
//                        }
//                    }
//                }
                Spacer(
                    Modifier.height(
                        currentWindowAdaptiveInfo1().windowSizeClass.paneVerticalPadding,
                    ),
                )
            }
        },
        modifier,
        windowInsets,
        navigationIcon = navigationIcon,
        layoutParameters = layoutParameters,
    )
}

@OptIn(ExperimentalMaterial3AdaptiveApi::class, ExperimentalMaterial3Api::class)
@Composable
internal fun SettingsPageLayout(
    navigator: ThreePaneScaffoldNavigator<Nothing?>,
    currentTab: () -> SettingsTab?,
    onSelectedTab: (SettingsTab) -> Unit,
    onClickBackOnListPage: () -> Unit,
    onClickBackOnDetailPage: () -> Unit,
    navItems: @Composable (SettingsDrawerScope.() -> Unit),
    tabContent: @Composable PaneScope.(currentTab: SettingsTab?) -> Unit,
    modifier: Modifier = Modifier,
    contentWindowInsets: WindowInsets = KmsWindowInsets.safeDrawing,
    containerColor: Color = KmsTheme.pageContentBackgroundColor,
    layoutParameters: ListDetailLayoutParameters = ListDetailLayoutParameters.calculate(navigator.scaffoldDirective),
    navigationIcon: @Composable () -> Unit = {},
) = Surface(color = containerColor) {
    val layoutParametersState by rememberUpdatedState(layoutParameters)
    val topAppBarScrollBehavior = if (LocalPlatform.current.hasScrollingBug()) {
        null
    } else {
        TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
    }

    val listPaneScrollState = rememberScrollState()
    AniListDetailPaneScaffold(
        navigator,
        listPaneTopAppBar = {
            TopAppBar(
                title = { Title("设置") },
                navigationIcon = {
                    if (navigator.canNavigateBack()) {
                        BackNavigationIconButton(
                            onNavigateBack = {
                                onClickBackOnListPage()
                            },
                        )
                    } else {
                        navigationIcon()
                    }
                },
                colors = AniThemeDefaults.transparentAppBarColors(),
                scrollBehavior = topAppBarScrollBehavior,
                windowInsets = paneContentWindowInsets.only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal),
            )
        },
        listPaneContent = paneScope@{
            PermanentDrawerSheet(
                Modifier
                    .paneContentPadding()
                    .paneWindowInsetsPadding()
                    .fillMaxWidth()
                    .ifThen(!LocalPlatform.current.hasScrollingBug()) {
                        topAppBarScrollBehavior?.let { nestedScroll(it.nestedScrollConnection) }
                    }
                    .verticalScroll(listPaneScrollState),
                drawerContainerColor = Color.Unspecified,
            ) {
                val highlightSelectedItemState =
                    rememberUpdatedState(layoutParametersState.highlightSelectedItem)
                val scope = remember(this, navigator, currentTab, highlightSelectedItemState) {
                    object : SettingsDrawerScope(), ColumnScope by this {
                        @Composable
                        override fun Item(item: SettingsTab) {
                            NavigationDrawerItem(
                                icon = { Icon(getIcon(item), contentDescription = null) },
                                label = { Text(getName(item)) },
                                selected = item == currentTab() && highlightSelectedItemState.value,
                                onClick = {
                                    onSelectedTab(item)
                                },
                            )
                        }
                    }
                }


                val verticalPadding =
                    currentWindowAdaptiveInfo1().windowSizeClass.paneVerticalPadding

                Spacer(Modifier.height(verticalPadding)) // scrollable
                navItems(scope)
                Spacer(Modifier.height(verticalPadding)) // scrollable
            }
        },
        // empty because our detailPaneContent already has it
        detailPane = {
            AnimatedContent(
                currentTab(),
                Modifier.fillMaxSize(),
                transitionSpec = LocalAniMotionScheme.current.animatedContent.topLevel,
            ) { navigationTab ->
                val tab = navigationTab.orDefault(layoutParametersState.isSinglePane)
                Column {
                    tab?.let {
                        TopAppBar(
                            title = {
                                Title(getName(tab))
                            },
                            navigationIcon = {
                                if (listDetailLayoutParameters.isSinglePane) {
                                    BackNavigationIconButton(
                                        {
                                            onClickBackOnDetailPage()
                                        },
                                    )
                                }
                            },
                            colors = AniThemeDefaults.transparentAppBarColors(),
                            windowInsets = paneContentWindowInsets.only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal),
                        )
                    }

                    Box(
                        Modifier
                            .fillMaxHeight()
                            .consumeWindowInsets(paneContentWindowInsets.only(WindowInsetsSides.Top)),
                    ) {
                        Column(
                            Modifier
                                .paneContentPadding(
                                    extraStart = -SettingsScope.itemHorizontalPadding,
                                    extraEnd = -SettingsScope.itemHorizontalPadding,
                                )
                                .paneWindowInsetsPadding(),
                        ) {
                            tabContent(tab)
                        }
                    }
                }
            }
        },
        modifier,
        layoutParameters = layoutParameters,
        contentWindowInsets = contentWindowInsets,
    )


}

@Composable
fun SettingItem(icon: ImageVector, title: String) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { /* Handle click */ }
            .padding(vertical = 12.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Icon(imageVector = icon, contentDescription = null)
        Spacer(modifier = Modifier.width(16.dp))
        Text(text = title, fontWeight = FontWeight.Bold)
    }
}

@Stable
abstract class SettingsDrawerScope internal constructor() : ColumnScope {
    @Composable
    abstract fun Item(item: SettingsTab)

    @Composable
    fun Title(text: String, paddingTop: Dp = 20.dp) {
        Text(
            text,
            Modifier
                .padding(horizontal = 8.dp)
                .padding(top = paddingTop, bottom = 12.dp),
            color = MaterialTheme.colorScheme.primary,
        )
    }
}